package com.nvshen.zhangmeiying.life;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nvshen.zhangmeiying.Constants;
import com.nvshen.zhangmeiying.R;
import com.nvshen.zhangmeiying.model.Article;
import com.nvshen.zhangmeiying.utils.*;
import org.apache.http.Header;

import java.io.IOException;

/**
 * Created by wxc on 14-8-10.
 */
public class HotListAdapter extends BaseArrayListAdapter<Article>
{
    Activity context;
//    IWeiboShareAPI weibo;
//    SsoHandler ssoHandler;

//    public HotListAdapter(Activity context, IWeiboShareAPI weibo, SsoHandler ssoHandler)
//    {
//        super(context);
//        this.context = context;
//
//        this.weibo = weibo;
//        this.ssoHandler = ssoHandler;
//    }

    public HotListAdapter(Activity context)
    {
        super(context);
        this.context = context;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        final Viewholder holder;
        if (convertView == null)
        {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_hot, null);
            holder = new Viewholder();
            holder.uAvaster = (CircleImageView) convertView.findViewById(R.id.hot_u_avastar);
            holder.uName = (TextView) convertView.findViewById(R.id.hot_u_name);
            holder.uTime = (TextView) convertView.findViewById(R.id.text_time);
            holder.follow = convertView.findViewById(R.id.hot_follow);
            holder.followImage = (ImageView) convertView.findViewById(R.id.follow_image);
            holder.followText = (TextView) convertView.findViewById(R.id.follow_text);
            holder.hotImage = (ImageView) convertView.findViewById(R.id.hot_image);
            holder.videoLayout = (RelativeLayout) convertView.findViewById(R.id.video_layout);
            holder.videoView = (VideoView) convertView.findViewById(R.id.videoView);
            holder.playBtn = (ImageView) convertView.findViewById(R.id.hot_play);
            holder.pauseBtn = convertView.findViewById(R.id.hot_pause);
            holder.description = (TextView) convertView.findViewById(R.id.hot_description);
            holder.location = (TextView) convertView.findViewById(R.id.text_location);

            holder.progressBar = (ProgressBar) convertView.findViewById(R.id.progress);

            // 新加的
            holder.layout_like_button = convertView.findViewById(R.id.layout_like_button);
            holder.button_like = (Button) convertView.findViewById(R.id.button_like);
            holder.text_like_number = (TextView) convertView.findViewById(R.id.text_like_number);
            holder.layout_gift_button = convertView.findViewById(R.id.layout_gift_button);
            holder.layout_im = convertView.findViewById(R.id.layout_im);
            holder.topLayout = (RelativeLayout) convertView.findViewById(R.id.hot_layout_top);
            holder.layout_share = convertView.findViewById(R.id.layout_share);
            holder.layout_private = convertView.findViewById(R.id.layout_private);
            holder.text_view_comment_number = (TextView) convertView.findViewById(R.id.text_view_comment_number);
            holder.text_view_private_hint = convertView.findViewById(R.id.text_view_private_hint);

            convertView.setTag(holder);
        }
        else
        {
            holder = (Viewholder) convertView.getTag();
        }

        final Article article = (Article) getItem(position);
        holder.uAvaster.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
//                ProfileTabActivity.getInstance(mContext, article.getUser());
            }
        });


        // 逻辑：女性，私密动态可见，出现提示文案；男性，私密动态不可见
        if (article.is_private == 1 && Constants.currentUser.gender == 1)
        {
            holder.text_view_private_hint.setVisibility(View.VISIBLE);
            holder.layout_private.setVisibility(View.GONE);
        }
        else
        {
            holder.text_view_private_hint.setVisibility(View.GONE);

            if (article.is_private == 1 && ArticleUtils.hasPurchased(getContext(), article.getId()) == false)
            {
                holder.layout_private.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.layout_private.setVisibility(View.GONE);
            }
        }

//        holder.layout_private.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                if (SharedPreferencesUtil.getBoolByName(Constants.USER_LOGIN_STATE, mContext))
//                {
//                    ArticleUtils.purchaseArticle(getContext(), article, new PurchaseResult()
//                    {
//                        @Override
//                        public void onSuccess()
//                        {
//                            notifyDataSetChanged();
//                        }
//
//                        @Override
//                        public void onFail(int code, String description)
//                        {
//
//                        }
//                    });
//                }
//                else
//                {
//                    LoginDialog.show(mContext);
//                }
//            }
//        });

//        holder.uName.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v)
//            {
//                ProfileTabActivity.getInstance(mContext, article.getUser());
//            }
//        });

        if (!TextUtils.isEmpty(article.getUser().getAvatar()))
        {
            if (holder.uAvaster.getTag() != null)
            {
                if (!holder.uAvaster.getTag().equals(article.getImage()))
                {
                    holder.uAvaster.setTag(article.getImage());
                    DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.avatar_loading).cacheOnDisc().cacheInMemory().build();
                    ImageLoader.getInstance().displayImage(article.getUser().getAvatar(), holder.uAvaster, options);
                }
            }
            else
            {
                holder.uAvaster.setTag(article.getImage());
                DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.avatar_loading).cacheOnDisc().cacheInMemory().build();
                ImageLoader.getInstance().displayImage(article.getUser().getAvatar(), holder.uAvaster, options);
            }
        }

        holder.text_view_comment_number.setText("" + article.getComment_number());

        holder.uName.setText(article.getUser().getNickname());
        holder.uTime.setText(TimeUtils.parseTime(article.getCreated_at()) + "");

        if (!TextUtils.isEmpty(article.getImage()))
        {
            if (holder.hotImage.getTag() != null)
            {
                if (!holder.hotImage.getTag().equals(article.getImage()))
                {
                    holder.hotImage.setTag(article.getImage());
                    DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.image_loading).cacheOnDisc().cacheInMemory().build();
                    ImageLoader.getInstance().displayImage(article.getImage(), holder.hotImage, options);
                }
            }
            else
            {
                holder.hotImage.setTag(article.getImage());
                DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.image_loading).cacheOnDisc().cacheInMemory().build();
                ImageLoader.getInstance().displayImage(article.getImage(), holder.hotImage, options);
            }
        }

        holder.description.setText(article.getDescription());
        if (!TextUtils.isEmpty(article.getCity()))
        {
            holder.location.setText(article.getProvince());
        }
        else
        {
            holder.location.setText("未知");
        }
        if (article.getVoted() == 1)
        {
            holder.layout_like_button.setBackgroundResource(R.drawable.button_square_cell_active);
            holder.button_like.setBackgroundResource(R.drawable.icon_like_active);
            holder.text_like_number.setTextColor(getContext().getResources().getColor(R.color.red_color));
        }
        else
        {
            holder.layout_like_button.setBackgroundResource(R.drawable.button_square_cell);
            holder.button_like.setBackgroundResource(R.drawable.icon_like_normal);
            holder.text_like_number.setTextColor(getContext().getResources().getColor(R.color.sub_text_color));
        }

        holder.text_like_number.setText(article.getVote() + "");

        if (!TextUtils.isEmpty(article.getVideo()))
        {
            holder.playBtn.setVisibility(View.VISIBLE);
            holder.playBtn.setImageResource(R.drawable.video_play);
        }
        else if (!TextUtils.isEmpty(article.getAudio()))
        {
            holder.playBtn.setVisibility(View.VISIBLE);
            holder.playBtn.setImageResource(R.drawable.audio_play);
        }
        else
        {
            holder.playBtn.setVisibility(View.GONE);
        }

        holder.playBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!TextUtils.isEmpty(article.getVideo()))
                {
                    addPlayTimes(article.getId());

                    holder.videoLayout.setVisibility(View.VISIBLE);
                    holder.playBtn.setVisibility(View.GONE);
                    holder.hotImage.setVisibility(View.INVISIBLE);

                    Uri uri = Uri.parse(article.getVideo());

                    holder.videoView.setMediaController(new MediaController(mContext));
                    holder.videoView.setVideoURI(uri);
                    holder.videoView.requestFocus();
                    holder.videoView.start();
                    holder.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
                    {
                        @Override
                        public void onCompletion(MediaPlayer mp)
                        {
                            holder.playBtn.setVisibility(View.VISIBLE);
                            holder.hotImage.setVisibility(View.VISIBLE);
                            holder.videoLayout.setVisibility(View.GONE);
                        }
                    });
                }
                else if (!TextUtils.isEmpty(article.getAudio()))
                {
                    addPlayTimes(article.getId());

                    holder.playBtn.setVisibility(View.INVISIBLE);
                    holder.progressBar.setVisibility(View.VISIBLE);
                    final MediaPlayer player = new MediaPlayer();
                    try
                    {
                        player.setDataSource(mContext, Uri.parse(article.getAudio()));
                        player.prepareAsync();
                        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
                        {
                            @Override
                            public void onPrepared(MediaPlayer mp)
                            {
                                holder.progressBar.setVisibility(View.INVISIBLE);
                                player.start();
                            }
                        });
                        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
                        {
                            @Override
                            public void onCompletion(MediaPlayer mp)
                            {
                                holder.playBtn.setVisibility(View.VISIBLE);
                            }
                        });
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }

//                notifyDataSetChanged();
            }
        });


        holder.layout_like_button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (SharedPreferencesUtil.getBoolByName(Constants.USER_LOGIN_STATE, mContext))
                {
                    if (article.getVoted() == 0)
                    {
                        article.setVote(article.getVote() + 1);
                        article.setVoted(1);
                        like(article.getId());
                    }
                    else
                    {
                        article.setVote(article.getVote() - 1);
                        article.setVoted(0);
                        cancelLike(article.getId());
                    }

                    notifyDataSetChanged();

                }
                else
                {
//                    LoginDialog.show(mContext);
                }
            }
        });

        if (article.getFollow_status() == 1)
        {
            holder.followImage.setVisibility(View.GONE);
            holder.followText.setText("已关注");
        }
        else
        {
            holder.followImage.setVisibility(View.VISIBLE);
            holder.followText.setText("关注");
        }
        holder.follow.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (SharedPreferencesUtil.getBoolByName(Constants.USER_LOGIN_STATE, mContext))
                {
                    if (article.getFollow_status() == 0)
                    {
                        for (int i = 0; i < getCount(); i++)
                        {
                            Article tempArticle = (Article) getItem(i);
                            if (tempArticle.getUser().getId() == article.getUser().getId())
                            {
                                tempArticle.setFollow_status(1);
                            }
                        }
                        notifyDataSetChanged();
                        follow(article.getUser().getId(), article.getId());
                    }
                    else
                    {
                        for (int i = 0; i < getCount(); i++)
                        {
                            Article tempArticle = (Article) getItem(i);
                            if (tempArticle.getUser().getId() == article.getUser().getId())
                            {
                                tempArticle.setFollow_status(0);
                            }
                        }
                        notifyDataSetChanged();
                        cancelFollow(article.getUser().getId());
                    }
                }
                else
                {
//                    LoginDialog.show(mContext);
                }
            }
        });

//        holder.layout_gift_button.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                if (SharedPreferencesUtil.getBoolByName(Constants.USER_LOGIN_STATE, mContext))
//                {
//                    GiveGiftActivity.getInstance(getContext(), article.getUser());
//                }
//                else
//                {
//                    LoginDialog.show(mContext);
//                }
//
//
//            }
//        });

//        holder.layout_im.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                if (SharedPreferencesUtil.getBoolByName(Constants.USER_LOGIN_STATE, mContext))
//                {
//                    ConversationActivity.getInstance(mContext, article.getUser());
//                }
//                else
//                {
//                    LoginDialog.show(mContext);
//                }
//            }
//        });
//
//        holder.layout_share.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                ArticleDetailActivity.showShareDialog(context, article, weibo, ssoHandler);
//            }
//        });
//
//        convertView.setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View view)
//            {
//                ArticleDetailActivity.getInstance(getContext(), article);
//            }
//        });


        holder.hotImage.setLayoutParams(new RelativeLayout.LayoutParams((int) Constants.SCREEN_WIDTH, (int) Constants.SCREEN_WIDTH));

        return convertView;
    }

    static class Viewholder
    {
        RelativeLayout topLayout;
        CircleImageView uAvaster;
        TextView uName;
        TextView uTime;
        View follow;
        ImageView followImage;
        TextView followText;
        ImageView hotImage;
        RelativeLayout videoLayout;
        VideoView videoView;
        ImageView playBtn;
        View pauseBtn;
        TextView description;
        TextView location;
        ProgressBar progressBar;

        // 新加的
        View layout_like_button;
        Button button_like;
        TextView text_like_number;
        TextView text_view_comment_number;
        View text_view_private_hint;

        View layout_gift_button;
        View layout_im;
        View layout_share;
        View layout_private;


    }


    private void addPlayTimes(int articleId)
    {
        NetUtils.get(UrlUtils.getAddPlayTimes(articleId), new PerfectAsyncHandler()
        {
            @Override
            public void onGetSuccess(Header[] header, String result)
            {
            }

            @Override
            public void onGetFailure(String errorCause)
            {
            }
        });
    }

    private void follow(int uid, int aid)
    {
        NetUtils.get(UrlUtils.getFollow(uid, aid, Constants.currentUser.getId()), new PerfectAsyncHandler()
        {
            @Override
            public void onGetSuccess(Header[] header, String result)
            {

            }

            @Override
            public void onGetFailure(String errorCause)
            {

            }
        });
    }

    private void cancelFollow(int uid)
    {
        NetUtils.get(UrlUtils.getCancelFollow(uid, Constants.currentUser.getId()), new PerfectAsyncHandler()
        {
            @Override
            public void onGetSuccess(Header[] header, String result)
            {

            }

            @Override
            public void onGetFailure(String errorCause)
            {

            }
        });
    }

    private void like(int articleId)
    {
        NetUtils.get(UrlUtils.getLike(Constants.currentUser.getId(), articleId), new PerfectAsyncHandler()
        {
            @Override
            public void onGetSuccess(Header[] header, String result)
            {
            }

            @Override
            public void onGetFailure(String errorCause)
            {
            }
        });
    }


    private void cancelLike(int articleId)
    {
        NetUtils.get(UrlUtils.getCancelLike(Constants.currentUser.getId(), articleId), new PerfectAsyncHandler()
        {
            @Override
            public void onGetSuccess(Header[] header, String result)
            {
            }

            @Override
            public void onGetFailure(String errorCause)
            {
            }
        });
    }

    private Activity getContext()
    {
        return context;
    }
}
